// import React, { Component } from 'react'
// import {useDispatch,useSelector} from 'umi'
import { useDispatch, useSelector } from 'umi'

import React, { useEffect, useState } from 'react'
import { Table, Tag, Space, Button, Pagination, Input, Select, DatePicker, Modal, Form, Radio, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import style from "./user.css"
import { addUser,updateUser,userDelete } from '../../apis/system';





const CollectionCreateForm = ({ visible, onCreate, onCancel }) => {
  const [form] = Form.useForm();
  const dept = useSelector((state) => {
    return state.system.dept
  })
  const role = useSelector((state) => {
    return state.system.role
  })
  // console.log(111,dept);
  return (
    <Modal
      visible={visible}
      title="新增用户"
      okText="添加"
      cancelText="关闭"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
        initialValues={{
          modifier: 'public',
        }}
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            {
              required: true,
              message: '请输入用户名',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            {
              required: true,
              message: '请输入邮箱!',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="mobile"
          label="电话"
          rules={[
            {
              required: true,
              message: '请输入电话号码!',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="角色ID" name='roleId'>
          <Select>
            {/* <Select.Option value="demo">Demo</Select.Option> */}
            {role ? role.rows.map(item => {
              return (
                <Select.Option value={item.roleId}>{item.roleName}</Select.Option>
              )
            }) : null}
          </Select>
        </Form.Item>
        <Form.Item label="部门ID" name='deptId'>
          <Select>
            {/* <Select.Option></Select.Option> */}
            {dept ? dept.map(item => {
              return (
                <Select.Option value={item.id}>{item.text}</Select.Option>
              )
            }) : null}
          </Select>
        </Form.Item>

        <Form.Item name="status" >
          <Radio.Group>
            <Radio value="1">有效</Radio>
            <Radio value="0">锁定</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item name="ssex" >
          <Radio.Group>
            <Radio value="0">男</Radio>
            <Radio value="1">女</Radio>
            <Radio value="2">保密</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default function user() {
  const [data, setData] = useState({ pageSize: 10, pageNum: 1 })
  const [form] = Form.useForm();
  const dispatch = useDispatch()
  const users = useSelector((state) => {
    return state.system.users
  })

  const dept = useSelector((state) => {
    return state.system.dept
  })
  const role = useSelector((state) => {
    return state.system.role
  })
  const getUser = () => {
    dispatch({
      type: 'system/getUsersBySaga',
      data
    })
  }
  const getDept = () => {
    dispatch({
      type: 'system/getDeptBySaga'
    })
  }
  const getRole = () => {
    dispatch({
      type: 'system/getRoleBySaga'
    })
  }
  useEffect(() => {
    getDept()
    getUser()
    getRole()
    // console.log(users);
  }, [])
  function onChange(current, pageSize) {
    console.log('Page: ', current, pageSize);
    setData({
      pageSize,
      pageNum: current
    })
    // getUser()
  }
  useEffect(() => {

    getUser()

    // console.log(users);
  }, [data])
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [userUpdate, setUserUpdate] = useState("wer")
  const onCreate = async (values) => {
    console.log(values);
    const res = await addUser(values)
    message.success('添加成功');

    setVisible(false);
  };

  const onCreate2 =async (values) => {
    // console.log(values);
    values.userId=userUpdate.userId
const res=await updateUser(values)
message.success('修改成功');



    setVisible2(false);
  };


  const onFinish = (values) => {
    console.log('Success:', values);
    setData({
      ...data,
      ...values
    })

  };

  const update = (val) => {
    setVisible2(true)
    console.log(val);
    setUserUpdate({
      ...val
    })
  }
const delateUser=async (id)=>{
// console.log(id);
const res=await userDelete(id)
// console.log(res);
message.success('删除成功');
getUser()

}
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: text => <a>{text}</a>,
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      key: 'ssex',
      render: text => {
        if (text == "0") {
          return "男"
        }
        else if (text == "1") {
          return "女"
        }
        else if (text == "2") {
          return "保密"
        }

      }
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: status => {

        if (status == '1') {
          return (
            <Tag color='green' >
              <span>有效</span>
            </Tag>
          )
        }
        else if (status == '0') {
          return (
            <Tag color='volcano' >
              <span>锁定</span>
            </Tag>
          )
        }
      }



    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },

    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Button type="dashed" onClick={() => update(text)
          }>修改</Button>
          <Button type="primary" danger onClick={()=>delateUser(text.userId)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];
  return (
    <div>
      <div className={style.box}>
        {/* 
        <div style={{ width: '27%' }}>
          <Input placeholder="请输入用户名" size='middle'  />
        </div>
        <div style={{ width: '27%' }}>
          <Select defaultValue="请选择部门" style={{ width: '100%' }}>
            <Option value="Zhejiang">Zhejiang</Option>
            <Option value="Jiangsu">Jiangsu</Option>
            {dept?dept.map(item=>{
              return(
                <Select.Option value={item.id}>{item.text}</Select.Option>
              )
            }):null}
          </Select>
        </div>
        <div style={{ width: '27%' }}>
          <DatePicker style={{ width: '100%' }} />
        </div> */}
        <Form
          name="basic"
          layout="inline"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 50,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}

          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"

          >
            <Input placeholder="请输入用户名" size='middle' />
          </Form.Item>
          <Form.Item
            label="部门"
            name="deptId"

          >
            <Select defaultValue="请选择部门" style={{ width: '100%' }}>
              {dept ? dept.map(item => {
                return (
                  <Select.Option value={item.id}>{item.text}</Select.Option>
                )
              }) : null}
            </Select>
          </Form.Item>
          <Form.Item
            label="日期"
            name="createTimeFrom"

          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" icon={<SearchOutlined />} htmlType="submit" >
              搜索
            </Button>
          </Form.Item>
        </Form>
        {/* <Button type="primary" icon={<SearchOutlined />} onClick={search}>
          查询
        </Button> */}
        <Button type="primary" onClick={() => {
          setVisible(true);
        }}>新增</Button>
      </div>

      <Table columns={columns} dataSource={users ? users.rows : null} pagination={false} /><br />
      <Pagination showQuickJumper defaultCurrent={1} total={users ? users.total : null} onChange={onChange} showSizeChanger />
      {/* pageSize={data.pageSize} current={data.pageNum} */}


      <CollectionCreateForm
        visible={visible}
        onCreate={onCreate}
        onCancel={() => {
          setVisible(false);
        }}

      />




      <Modal
        visible={visible2}
        title="修改用户"
        okText="修改"
        cancelText="关闭"
        onCancel={() => {
          setVisible2(false);
        }}
        destroyOnClose
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate2(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          >
            <Input defaultValue={userUpdate?userUpdate.username:null} ></Input>
          </Form.Item>
            {/* {userUpdate} */}
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              {
                required: true,
                message: '请输入邮箱!',
              },
            ]}
          >
            <Input defaultValue={userUpdate?userUpdate.email:null}  />
          </Form.Item>
          <Form.Item
            name="mobile"
            label="电话"
            rules={[
              {
                required: true,
                message: '请输入电话号码!',
              },
            ]}
          >
            <Input defaultValue={userUpdate?userUpdate.mobile:null}/>
          </Form.Item>
          <Form.Item label="角色ID" name='roleId'  rules={[
              {
                required: true,
                message: '请选择角色',
              },
            ]}>
            <Select>
              {/* <Select.Option value="demo">Demo</Select.Option> */}
              {role ? role.rows.map(item => {
                return (
                  <Select.Option value={item.roleId}>{item.roleName}</Select.Option>
                )
              }) : null}
            </Select>
          </Form.Item>
          <Form.Item label="部门ID" name='deptId'  rules={[
              {
                required: true,
                message: '请选择部门',
              },
            ]}>
            <Select>
              {/* <Select.Option></Select.Option> */}
              {dept ? dept.map(item => {
                return (
                  <Select.Option value={item.id}>{item.text}</Select.Option>
                )
              }) : null}
            </Select>
          </Form.Item>

          <Form.Item name="status"  rules={[
              {
                required: true,
                message: '请选择状态',
              },
            ]}>
            <Radio.Group defaultValue={userUpdate?userUpdate.status:null}>
              <Radio value="1">有效</Radio>
              <Radio value="0">锁定</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item name="ssex"  rules={[
              {
                required: true,
                message: '请选择性别',
              },
            ]}>
            <Radio.Group defaultValue={userUpdate?userUpdate.ssex:null}>
              <Radio value="0">男</Radio>
              <Radio value="1">女</Radio>
              <Radio value="2">保密</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

